#include<string>
#include<iostream>
#include<sys/socket.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<unistd.h>
#include<cstring>
#include<pthread.h>

void usage(std::string proc)
{
    std::cout << proc << " server_ip server_port" << std::endl;
}

void* Routine(void * args)
{
    pthread_detach(pthread_self());
    int sock = *(int*)args;
    delete args;
    char buff[1024];
    while(true)
    {
        memset(buff,0,sizeof buff);
        int s = read(sock,buff,sizeof buff - 1);
        if(s == 0 )
        {
            std::cerr << "server quit.... " << errno << std::endl;
            break;
        } 
        else if(s < 0)
        {
            std::cerr << "read error  " << errno << std::endl;
            break;
        }
        else
        {
            buff[s] = 0;
            std::cout << buff << std::endl;
        }
    }
}

int main(int argc , char* argv[])
{
    if(argc != 3)
    {
        usage(argv[0]);
        return 1;
    }
    //create
    int sock = socket(AF_INET,SOCK_STREAM,0);
    if(socket < 0)
    {
        std::cerr << "socket error  " << errno << std::endl;
        return 2;
    }

    //bind 自动

    //connect 向服务器发起连接
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons((uint16_t)atoi(argv[2]));
    server.sin_addr.s_addr = inet_addr(argv[1]);
    if(connect(sock,(struct sockaddr*)&server,sizeof server) < 0 )
    {
        std::cerr << "connect error  " << errno << std::endl;
        return 3;
    }
    std::cout << "connect succeed " << std::endl;

    //创建一个线程接收消息
    pthread_t tid;
    int* ssock = new int(sock);
    pthread_create(&tid,nullptr,Routine,(int*)ssock);

    //主线程写
    while(true)
    {
        std::string message;
       //std::cout << "请输入 ##" ;
        std::cin >> message;
        write(sock,message.c_str(),message.size());
    }
    return 0 ;
}